import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution02 {
    public int[][] merge(int[][] intervals) {
        // 对二维数组 左端点 进行排序 从小到大升序
        Arrays.sort(intervals, (v1, v2) -> {
            return v1[0] - v2[0];
        });
        // 合并区间
        int left = intervals[0][0], right = intervals[0][1];
        // 定义结果
        List<List<Integer>> ret = new ArrayList<>();
        for (int i = 1; i < intervals.length; i++) {
            List<Integer> list = new ArrayList<>();
            int a = intervals[i][0], b = intervals[i][1];
            // 进行分类讨论
            if (a <= right) {
                right = Math.max(right, b);
            } else {
                list.add(left);
                list.add(right);
                ret.add(list);
                left = a;
                right = b;
            }
        }
        ret.add(Arrays.asList(left, right));
        // 将结果从 List 转换为 int[][] 数组并返回
        int[][] result = new int[ret.size()][2];
        for (int i = 0; i < ret.size(); i++) {
            result[i][0] = ret.get(i).get(0);
            result[i][1] = ret.get(i).get(1);
        }
        return result;
    }
}